<?php
/**
 * 积分订单服务层
 * @author maniac
 */
namespace app\common\service;

use app\common\model\WechatUsers AS WechatUsersModel;
use app\common\model\MemberAddresses AS MemberAddressesModel;
use app\common\model\PointOrders AS PointOrdersModel;
use app\common\model\PointGoods AS PointGoodsModel;
use app\common\model\Point AS PointModel;
use app\common\model\PointSku AS PointSkuModel;
use app\common\model\Members AS MembersModel;
use app\facade\Point AS PointFacade;
use app\facade\Options AS OptionsFacade;
use app\facade\Members AS MembersFacade;
use think\Db;

class PointOrders extends Base
{
    /**
     * 确认订单
     * @param $data
     */
    public function confirmOrder($data)
    {
        $orderAmount = 0;       // 订单金额
        $goodsIds = [];      // 商品 id
        $goodsSkuIds = [];      // 商品 sku id
        $temp = [];      // 商品信息临时数组
        if (!is_array($data['goods'])) {
            $data['goods'] = json_decode($data['goods'], true);
        }
        foreach ($data['goods'] as $v) {
            if ($v['goods_sku_id']) {
                $goodsSkuIds[] = $v['goods_sku_id'];
            } else {
                $goodsIds[] = $v['goods_id'];
            }
            $temp[$v['goods_id']] = $v;
        }
        $where = [
            ['id', 'in', array_keys($temp)],
        ];


        $goods = PointModel::field('id,goods_name,point,goods_stock,goods_thumb_id,give_points,goods_stock,dis_money,dis2_money')
            ->append(["image_uri"])->where($where)->select()->toArray();

        if (empty($goods) || count($goods) == 0) {
            exception('商品不存在');
        }
        foreach ($goods as $k=>$v) {
            if (in_array($v['id'], $goodsIds)) {
                $orderAmount += $v['point'] * $temp[$v['id']]['goods_nums'];
            }
            $updateGoods[] = [
                'id' => $v['id'],
                'goods_stock' => $v['goods_stock'] - $temp[$v['id']]['goods_nums'],
            ];

            $goods[$k]['goods_nums'] =$temp[$v['id']]['goods_nums'];
            $goods[$k]['goods_id']=$v['id'];
            $goods[$k]['sku_x']="";
            $goods[$k]['goods_sku_id']="";
        }

        $member_info = MembersFacade::info($data['userid']);//查询用户信息
        $list = $goods;
        //团购没有属性价格
        if (!empty($goodsSkuIds) && $data['buyType'] !=2) {
            // 存在商品 sku，以商品 sku 的库存和销售价格计算
            $where = [
                ['sku_id', 'in', $goodsSkuIds],
                ['goods_id', 'in', array_keys($temp)],
            ];
            $sku = PointSkuModel::field('id,goods_id,sku_name,point,stock')->where($where)->select();

            $orderAmount=0;
            if(!empty($sku)){
                $list = [];
                foreach ($sku as $k => $uv) {
                    foreach($goods as $gk=>$gv){
                        if($gv['id']==$uv['goods_id']){
                            $list[$k] = $gv;
                            $orderAmount += $uv['point'] * $gv['goods_nums'];
                            $list[$k]['sale_price']=$uv['point'];
                            $list[$k]['goods_name']=$gv['goods_name'];
                            $list[$k]['sku_x']=$uv['sku_name'];
                            $list[$k]['goods_sku_id']=$uv['id'];
                        }
                    }
                }
            }
        }
        $orderInfo["goods"] = $list;
        $orderInfo["orderAmount"] = $orderAmount;
        return $orderInfo;
    }




    /**
     * 添加订单
     * @param array $data 请求的信息
     */
    public function add($data)
    {
        // 微信用户信息
        $user        = WechatUsersModel::field('openid,nickname')->where('id', $data['userid'])->find();
        // 会员信息
        $member      = MembersModel::field('id,wechat_id,role_id,points,balance,nickname')->where('wechat_id', $data['userid'])->find();
        // 收货地址信息
        $address     = MemberAddressesModel::field('name,mobile,province,city,district,address')->append(['province_txt','city_txt','district_txt'])
            ->where('id', $data['user_address_id'])->find();

       	$updateSku   = [];
       	
       	$updateGoods = [];
       	
       	$where = [
       		'id'  => $data['goods_id'],
       	];
		$goods = PointModel::field('id,goods_name,point,goods_stock,goods_thumb_id,give_points,goods_stock,dis_money,dis2_money')->where($where)->find();
		
		if (!empty($data['goods_sku_id'])) {
			// 存在商品 sku，以商品 sku 的库存和销售价格计算
			$wheres = [
			
				'id'  => $data['goods_sku_id'],
				
				'goods_id'  => $data['goods_id'],
				
			];
			$sku = PointSkuModel::field('id,goods_id,sku_name,point,stock')->where($wheres)->find();
			
			if ($data['goods_nums'] > $sku['stock']) {
				
				exception('库存不足!');
				
			}
			
			$goods_sku_name = $sku['sku_name'];
			
			$point = $sku['point']*$data['goods_nums'];
			
			$updateSku[] = [
			
				'id'    => $sku['id'],
				
				'stock' => $sku['stock'] - $data['goods_nums'],
				
			];
		
		}else{
			
			if ($data['goods_nums'] > $goods['goods_stock']) {
				
				exception('库存不足');
				
			}
			
			$goods_sku_name ='';
			
			$point = $goods['point']*$data['goods_nums'];
			
			$updateGoods[] = [
			
				'id'          => $data['goods_id'],
				
				'goods_stock' => $goods['goods_stock'] - $data['goods_nums'],
				
			];
			
		}	
		
		if ($point > $member['points']) {
			
			exception('用户积分不足');
			
		}else{
			
			$updateMember[] = [
				
				'id'    => $data['userid'],

				'wechat_id'    => $member['wechat_id'],

				'points' => $member['points'] - $point,
			
			];
		}
		
//		$options = unserialize(OptionsFacade::option('shop_info'));
//
//		$freight = $options['shop_freight'];
		
        $data['order_no']           = time().mt_rand(100000, 999999);
        
        $data['out_trade_no']       = unid();

        $data['userid']           	= $data['userid'];
        
        $data['username']           = $user['nickname'];
        
        $data['user_message']       = $data['user_message']; //买家留言
        
        $data['receiver_name']      = $address['name'];
        
        $data['receiver_mobile']    = $address['mobile'];
        
        $data['receiver_province']  = $address['province_txt'];
        
        $data['receiver_city']      = $address['city_txt'];
        
        $data['receiver_district']  = $address['district_txt'];
        
        $data['receiver_address']   = $address['address'];
        
        $data['points']              = $point;
        
        $data['order_amount']       = 0;
        
        $data['pay_amount']         = 0;
        $order                      = PointOrdersModel::create($data);
        
        if ($order->id) {
            //积分商品
            $orderGoods[] = [
                'order_id'    => $order->id,
                'goods_id'    => $goods['id'],
                'goods_name'  => $goods['goods_name'],
                'sku_id'      => $sku['id'],
                'sku_name'    => $sku['sku_name'],
                'sale_price'  => 0,
                'goods_nums'  => $data['goods_nums'],
                'image_uri'   => $goods['image_uri'],
                'point'   => $sku['point'],
            ];

            (new PointGoodsModel)->saveAll($orderGoods);
            // 修改商品表库存
            (new PointModel)->saveAll($updateGoods);
            // 修改商品 sku 库存
            (new PointSkuModel)->saveAll($updateSku);
            //积分记录
            $datas = [

                'id'=>$data['userid'],

                'key'=>'points',

                'value'=>'-'.$point,

                'remark'=>'使用积分购买商品',

                'sort'=>2,

                'surplus' => $member['points'] - $point,

            ];

            MembersFacade::balanceChange($datas);


            // 修改 用户积分数量
            (new MembersModel)->saveAll($updateMember);


            $result = [];
			$result['order_id'] = $order->id;
			$result['pay_amount'] = $data['pay_amount'] ;

            return $result;
            
        }
        
        exception('添加订单失败');
        
    }
    
    /**
     * 删除订单
     * @param int    $id   订单 id
     */

    public function del($id,$userid){
    	
        $order_goods = $this->orderInfo($id, $userid);
        
        if($order_goods['sku_id']==0){
        	
            $goods=db('point')->where('id',$order_goods['goods_id'])->setInc('goods_stock',$order_goods['goods_nums']);
        
        }else{
        	
            $goods=PointSkuModel::field(true)->where('id',$order_goods['sku_id'])->setInc('stock',$order_goods['goods_nums']);
        
        }
        if ($order_goods['pay_status'] == 0) {
        	//更新用户积分以积分记录
        	$data = [
        	
	        	'id'=>$userid,
	        	 
	        	'key'=>'points',
	        	 
	        	'value'=>$order_goods['points'],
	        	 
	        	'remark'=>'删除订单，返还积分',
	        	 
	        	'sort'=>1,
        	
        	];
        	
        	MembersFacade::balanceChange($data);
        	
        	$members = MembersModel::field('id,role_id,points,balance')->where('wechat_id', $userid)->find();
        	
        	$members->points = ['inc', $order_goods['points']];
        	
        	$members->save();
        }

        
        PointOrdersModel::where('id',$id)->delete();
        
        if(isset($goods)){
        	
            return $goods;
            
        }
        
        exception('删除订单失败');
        
    }

    
    /**
     * 获取订单列表
     * @param int    $userId   用户 id
     * @param string $limit    分页条件
     * @param int    $tabIndex 索引
     */
    public function orderList($userId, $limit, $tabIndex)
    {
        $where[] = [
        
            ['is_user_delete', 'eq', 0],
            ['userid', 'eq', $userId],
            
        ];
        
        
        
        switch ($tabIndex) {
        	case 1:
        		// 待付款
        		$where[] = [
        	
        		['order_status', 'eq', 1],
        	
        		['pay_status', 'eq', 0],
        	
        		];
        	
        		break;
        	
            case 2:
                // 待发货
                $where[] = [
                
                    ['order_status', 'eq', 1],
                    
                    ['pay_status', 'eq', 1],
                    
                    ['shipping_status', 'eq', 0],
                    
                ];
                
                break;
                
            case 3:
                // 待收货
                $where[] = [
                
                    ['order_status', 'eq', 1],
                    
                    ['pay_status', 'eq', 1],
                    
                    ['shipping_status', 'eq', 1],
                    
                ];
                
                break;
                
            case 4:
                // 已完成
                $where[] = [
                
                    ['order_status', 'eq', 255],
                    
                ];
                
                break;
                
        }
        
        $data = PointOrdersModel::field(true)->append(['order_status_id', 'order_status_txt','goods_list'])
            ->where($where)->order('id DESC')->limit($limit)->select();
        return $data;
        
    }
    
    /**
     * 获取订单详情
     * @param int $userId 用户 id
     * @param int $id     订单 id
     */
    public function orderInfo($id, $userId = 0)
    {
        
        if (!$id) {
        	
            exception('订单不存在');
            
        }
        
        $where[] = [
        
            ['id', 'eq', $id],
            
            ['userid', 'eq', $userId],
            
            
        ];

        $orderinfo=PointOrdersModel::field('id,userid,goods_id,sku_id,goods_nums,user_message,order_no,out_trade_no,pay_type,order_amount,pay_amount,points,order_status,pay_status,shipping_status,sign_time,finish_time,receiver_province,receiver_city,receiver_district,receiver_name,receiver_mobile,receiver_address,create_time')->where($where)->find();
        
        if (!empty($orderinfo)) {
        	$wheres = [
        	
        		'id'=>$orderinfo['goods_id'],
        	
        	];
        	
        	$goods = PointFacade::point($wheres,'','','');
        	
        	$orderinfo['goods_list']=$goods;
        	
//         	$province=Db::name('diqu')->where('region_id',$orderinfo['receiver_province'])->value('region_name');
        	
//         	$city=Db::name('diqu')->where('region_id',$orderinfo['receiver_city'])->value('region_name');
        	
//         	$district=Db::name('diqu')->where('region_id',$orderinfo['receiver_district'])->value('region_name');
        	
        	$orderinfo['create_time_frm']=date('Y-m-d H:i:s',$orderinfo['create_time']);
        	
        	$orderinfo['address']=array(
        	
        			'receiver_name'=>$orderinfo['receiver_name'],
        	
        			'receiver_mobile'=>$orderinfo['receiver_mobile'],
        	
        			'receiver_address'=>$orderinfo['receiver_province'].$orderinfo['receiver_city'].$orderinfo['receiver_district'].$orderinfo['receiver_address']
        	);
        	
        }
        $options = unserialize(OptionsFacade::option('shop_info'));
        $orderinfo['freight'] = $options['shop_freight'];
        return $orderinfo;



    }
     
    /**
     * 确认收货
     * @param int $userId 用户 id
     * @param int $id     订单 id
     */
    public function confirmGoods($userId, $id)
    {
        
        $order = $this->orderInfo($id, $userId);
        
        if (!$order) {
        	
            exception('订单不存在');
            
        }
        
        if ($order['order_status'] == 255) {
        	
            exception('该订单已完成');
            
        }
        
        $order->shipping_status = 2;
        
        $order->order_status    = 255;
        
        $order->sign_time       = time();
        
        $order->finish_time     = time();
        
        if ($order->save()) {
    			
            return true;
            
        }
        
        return false;
    }
    
   

    /**
    
    * 更新商品销量
    
    * @param int $order_id 订单 id
    
    */
    
    private function updateGoodsSaleNums($order_id,$userid)
    
    {
    
    	$order_goods = $this->orderInfo($order_id, $userid);
        
        if($order_goods['sku_id']==0){
        	
            $goods=db('point')->where('id',$order_goods['goods_id'])->setDec('goods_stock',$order_goods['goods_nums']);
        
        }else{
        	
            $goods=PointSkuModel::field(true)->where('id',$order_goods['sku_id'])->setDec('stock',$order_goods['goods_nums']);
        
        }
    
    }
    
}
